package br.igk.hibernate;


import java.io.File;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtility {
	private static Session session;
	private static SessionFactory factory;
	private static Transaction transaction;
	private static Configuration conf;


	public static Session getSession() {
		return session;
	}


	public static void openTransaction() {
		try {
			if (conf == null && session == null) {
				conf = new AnnotationConfiguration();
				conf.configure(new File("./src/br/igk/config/hibernate/hibernate.cfg.xml"));
				factory = conf.buildSessionFactory();
				session = factory.openSession();
			}
			transaction = session.beginTransaction();
		} catch (Exception e) {
			e.printStackTrace();
			session = null;
			factory = null;
			conf = null;
			transaction = null;
		}
	}


	public static void commit() {
		transaction.commit();
	}


	public static void rollback() {
		transaction.rollback();
	}


	public static void commitAndClose() {
		transaction.commit();
		session.close();
		clean();
	}


	public static void clean() {
		session = null;
		factory = null;
		conf = null;
		transaction = null;
	}
}